<template>
  <div class="container">

    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="商品标题" prop="name">
        <el-input v-model="ruleForm.name" style="width:800px" />
      </el-form-item>

      <el-form-item label="商品分类" prop="cat_id">
        <el-select v-model="ruleForm.cat_id" placeholder="请选择" style="width:800px">
          <el-option
            v-for="item in classifyData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="售价" prop="selling_price">
        <el-input v-model="ruleForm.selling_price" type="number" style="width:800px" />
      </el-form-item>

      <el-form-item label="商品封面图" prop="image">
        <el-upload
          class="uploadImg"
          :action="UPLOAD_URL"
          list-type="picture-card"
          name="image"
          :limit="1"
          :file-list="imgFileList"
          :on-success="handleSuccess"
          :on-preview="previewImg"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item label="商品主图" prop="banner">
        <el-upload
          class="uploadImg"
          :action="UPLOAD_URL"
          list-type="picture-card"
          name="image"
          :multiple="true"
          :file-list="bannerFileList"
          :on-success="handleSuccess2"
          :on-preview="previewImg"
          :on-remove="handleRemove2"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item label="商品内容" prop="content">
        <div class="wangEdit" style="width:800px">
          <WangEditor v-model="ruleForm.content" />
        </div>
      </el-form-item>

      <el-form-item label="虚拟销量" prop="void_sale">
        <el-input v-model="ruleForm.void_sale" type="number" style="width:800px" />
      </el-form-item>

      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="ruleForm.stock" :min="1" :max="9999" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" type="number" style="width:800px" />
        <p class="hint">请输入数字，序号越大排序越靠前</p>
      </el-form-item>

      <el-form-item label="上架状态" prop="status">
        <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>

    <div class="btn">
      <el-button @click="$router.back()">返回</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitForm('ruleForm')">确 定</el-button>
    </div>

    <!-- 预览图片 -->
    <el-dialog :visible.sync="isImg" width="500px">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { UPLOAD_URL } from '@/env'
import WangEditor from '@/components/wangEditor/wangEditor.vue'
export default {
  components: { WangEditor },
  data() {
    return {
      btnLoading: false,
      UPLOAD_URL,
      dialogImageUrl: '',
      isImg: false,

      editId: '',
      ruleForm: {
        name: '',
        image: '',
        banner: [],
        void_sale: 0,
        status: 1,
        sort: 1,
        stock: 1,
        cat_id: '',
        selling_price: '',
        content: ''
      },

      imgFileList: [], // 主图回显
      bannerFileList: [], // banner图回显

      rules: {
        name: { required: true, message: '请填写商品名称', trigger: 'blur' },
        cat_id: { required: true, message: '请选择商品分类', trigger: 'blur' },
        selling_price: { required: true, message: '请填写商品售价', trigger: 'blur' },
        image: { required: true, message: '请上传商品封面图', trigger: 'blur' },
        banner: { required: true, message: '请上传商品主图', trigger: 'blur' }
      },

      classifyData: [] // 分类
    }
  },
  created() {
    this.getClassifyData()
    this.$route.query.id && this.getGoodsDetails()
  },
  methods: {

    // 获取回显数据
    getGoodsDetails() {
      this.$request.get(`/admin/goods/details/${this.$route.query.id}`).then(res => {
        if (res.code == 200) {
          const { id, name, image, banner, void_sale, status, sort, cat_id, selling_price, content, stock } = res.data
          const bannerArry = banner.split(',')

          this.ruleForm = { id, name, image, banner: bannerArry, void_sale, status: Number(status), sort, cat_id, selling_price, content, stock }
          this.imgFileList = [{ url: image }]
          this.bannerFileList = bannerArry.map(item => { return { url: item } })
        }
      }).catch()
    },

    // 获取分类数据
    getClassifyData() {
      this.$request.get('/admin/goods_category').then(res => {
        this.classifyData = res.data.data
      }).catch()
    },

    // 添加商品
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.ruleForm.banner = this.ruleForm.banner.join(',')
          this.$request.post('/admin/goods/save', this.ruleForm).then(res => {
            this.btnLoading = false
            if (res.code == 200) {
              this.$message.success(this.$route.query.id ? '编辑成功' : '添加成功')
              this.$router.back()
            }
          }).catch(_ => { this.btnLoading = false })
        }
      })
    },

    // 清除验证
    resetForm(formName) {
      this.$refs[formName].clearValidate()
    },

    // 商品封面图上传
    handleSuccess(res) {
      if (res.code == 200) {
        this.imgFileList = [{ url: res.data.path }]
        this.ruleForm.image = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove() {
      this.imgFileList = []
      this.ruleForm.image = ''
    },

    // 商品主图上传
    handleSuccess2(res) {
      if (res.code == 200) {
        this.ruleForm.banner.push(res.data.path)
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove2(res, fileList) {
      this.ruleForm.banner = fileList.map(item => item.response.data.path)
    },

    // 预览图片
    previewImg(file) {
      this.dialogImageUrl = file.url
      this.isImg = true
    }
  }
}
</script>
<style scoped>
    .wangEdit /deep/ .w-e-text-container {
      height: 500px !important;
    }
</style>
<style lang="scss" scoped>
    .container{
        width: 100%;
        height: 100%;
        background-color: #fff;
        padding: 20px;
        overflow-y: scroll;
        &::-webkit-scrollbar { width: 0 !important }
    }
    .hint{
        margin: 0;
        padding: 0;
        color: #aaa;
        font-size: 12px;
    }
    .uploadImg ::v-deep .el-upload--picture-card{
      height:100px;
      width:100px;
      line-height: 104px;
    }
    .uploadImg ::v-deep .el-upload-list--picture-card .el-upload-list__item{
      height:100px;
      width:100px;
      line-height: 104px;
    }
    .uploadImg ::v-deep .el-icon-upload-success{
      position: absolute;
      right: 15px;
      top: 0px;
    }

    .btn{
        width: 100%;
        display: flex;
        justify-content: center;
    }

    .pvmimg{
        width: 500px;
    }
</style>
